package com.xunmall.wechat.controller;

import com.xunmall.wechat.model.constant.WeChatLinkConstant;
import com.xunmall.wechat.model.constant.WeChatURLConstant;
import com.xunmall.wechat.service.WeChatOfficialService;
import com.xunmall.wechat.util.wechat.WeChatGlobalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Random;

/**
 * @Author: WangYanjing
 * @Date: 2019/1/17 14:29
 * @Description:
 */
@Controller
@RequestMapping(value = "/main")
public class OpenMainController extends BaseWeChatController {

    @Autowired
    private WeChatOfficialService weChatOfficialService;

    @RequestMapping(value = "/switch", method = RequestMethod.GET)
    public void switchMain(@RequestParam(value = "location", required = false) String location, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String lev2Domain = parseDomain(request);
        System.out.println(lev2Domain);
        //通过二级域名查询相关的微信公众号配置
        Map<String, String> wechatMap = weChatOfficialService.getBaseConfigByChannel(lev2Domain);
        String appId = WeChatLinkConstant.APP_ID;
        if (!wechatMap.isEmpty()) {
            appId = wechatMap.get("APP_ID");
        }
        String backUrl = "http://wangyanjing-test.ichile.com.cn/main/callback";
        String target = WeChatURLConstant.QUIET_LOGIN_CODE_URL.replace("APP_ID", appId)
                .replace("REDIRECT_URI", URLEncoder.encode(backUrl, "UTF-8")).replace("STATE", lev2Domain);
        response.sendRedirect(target);
    }

    @RequestMapping(value = "/callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");
        String channel = request.getParameter("state");
        System.out.println(code);
        System.out.println(channel);
        Map<String, String> wechatMap = weChatOfficialService.getBaseConfigByChannel(channel);
        String appId = WeChatLinkConstant.APP_ID;
        String appSecret = WeChatLinkConstant.APP_SECRET;
        if (!wechatMap.isEmpty()) {
            appId = wechatMap.get("APP_ID");
            appSecret = wechatMap.get("APP_SECRET");
        }
        String openId = WeChatGlobalUtils.getQuietOpenId(appId, appSecret, code);
        System.out.println(openId);
        Random random = new Random();
        if (random.nextInt() % 2 == 0) {
            response.sendRedirect("http://m.yemaodc.xyz/");
        } else {
            response.sendRedirect("http://m.dingtingtech.xyz/");
        }
    }

}
